package cn.fl.ref.account.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.account.service.IFncGroupCompanyAccountService;
import cn.fl.ref.account.service.IFncGroupCompanyService;
import cn.fl.ref.account.vo.FncGroupCompanyAccountVO;
import cn.fl.system.constant.SysLogConstant;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.ref.account.condition.FncGroupCompanyAccountQueryCondition;
import fl.ref.account.condition.FncGroupCompanyQueryCondition;
import fl.ref.account.constant.FncGroupCompanyConstants;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;

/**
 * @Description: 集团公司账户
 */
@Controller
@RequestMapping("/account/fncGroupCompanyAccount")
public class FncGroupCompanyAccountController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FncGroupCompanyAccountController.class);

	@Autowired
	private IFncGroupCompanyService fncGroupCompanyService;
	@Autowired
	private IFncGroupCompanyAccountService fncGroupCompanyAccountService;
	@Autowired
	private ICstBscInfoService cstBscInfoService;// 客户
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * 跳转到列表页面
	 */
	@RequestMapping("/toListPage.do")
	public String toListPage(HttpServletRequest request) {

		// 客户类型
		request.setAttribute("cstTypCdList", this.cstBscInfoService.searchCstTypCdList());
		request.setAttribute("from", request.getParameter("from"));
		
		this.toSave(request);
		
		return "rfbase/account/fncGroupCompanyAccountList";
	}

	/**
	 * 列表页面查询
	 */
	@RequestMapping("/initList.do")
	@ResponseBody
	public Object initList(FncGroupCompanyAccountQueryCondition qc, HttpServletRequest request) {

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String bank = request.getParameter("bank");
		
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		if (StringUtils.isNotEmpty(bank)) {
			// 银行(数据字典)
			List<KeyValueVO> bankList = sysDictionaryApiService.getKvList(FncGroupCompanyConstants.FNC_BANK,
					CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
			if(CollectionUtils.isNotEmpty(bankList)) {
				List<String>  banks = new ArrayList<String>();
				for (KeyValueVO keyValueVO : bankList) {
					if(StringUtils.isNotBlank(keyValueVO.getValue())
							 && keyValueVO.getValue().contains(bank)) {
						banks.add(keyValueVO.getKey());
					}
				}
				if(CollectionUtils.isEmpty(banks)) {
					banks.add("-1");
				}
				qc.setBanks(banks);
			}
		}
		
		
		qc.setIsDel(FncGroupCompanyConstants.IS_DEL_NO);
		page.setCondition(qc);

		Pager pager = this.fncGroupCompanyAccountService.searchListPage(page);
		ListPageVO<FncGroupCompanyAccountVO> listPage = new ListPageVO<FncGroupCompanyAccountVO>(
				(List<FncGroupCompanyAccountVO>) pager.getResultList(), pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page),
				CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 跳转到集团公司账户新增或修改页面
	 */
	@RequestMapping(value = "/toSave.do")
	public Object toSave(HttpServletRequest request) {

		request.setAttribute("operate", request.getParameter("operate"));

		// 所属集团公司
		FncGroupCompanyQueryCondition qc = new FncGroupCompanyQueryCondition();
		qc.setIsDel(FncGroupCompanyConstants.IS_DEL_NO);
		request.setAttribute("fncGroupCompanyList", fncGroupCompanyService.selectList(qc));

		// 账户归属部门
		List<KeyValueVO> orgList = sysDictionaryApiService.getKvList(FncGroupCompanyConstants.ORG_CD,
				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		request.setAttribute("buOrgCdList", orgList);
		
//		// 开户银行(数据字典)
//		List<KeyValueVO> bankList = sysDictionaryApiService.getKvList(FncGroupCompanyConstants.FNC_BANK,
//				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
//		request.setAttribute("bankList", bankList);

		// 账户状态(数据字典)
		request.setAttribute("accountStatusList",
				sysDictionaryApiService.getKvList(FncGroupCompanyConstants.FNC_ACCOUNT_STATUS,
						CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()));

		// 币种(数据字典)
		request.setAttribute("currencyList",
				sysDictionaryApiService.getKvList(FncGroupCompanyConstants.FNC_ACCOUNT_CURRENCY,
						CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()));

		// 账户性质(数据字典)
		request.setAttribute("bankNatureList",
				sysDictionaryApiService.getKvList(FncGroupCompanyConstants.FNC_ACCOUNT_BANK_NATURE,
						CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()));

		String id = (String) request.getParameter("id");
		if (StringUtils.isNotBlank(id)) {
			request.setAttribute("fncGroupCompanyAccountVO",
					fncGroupCompanyAccountService.selectById(Long.valueOf(id)));
		}
		request.setAttribute("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		request.setAttribute("loginUsrNm", CurrentThreadContext.getCurrentUserName());

		return "rfbase/account/fncGroupCompanyAccountSave";
	}

	/**
	 * 跳转到集团公司账户发起流程
	 */
	@RequestMapping(value = "/toStartFlow.do")
	public Object toStartFlow(String operate, HttpServletRequest request) {

		this.toSave(request);

		FncGroupCompanyAccountVO fncGroupCompanyAccountVO = (FncGroupCompanyAccountVO) request
				.getAttribute("fncGroupCompanyAccountVO");
		if (fncGroupCompanyAccountVO == null) {
			BaseLogUtils.error(logger, null, "没有查到账户信息,fncGroupCompanyAccountVO不能为空",
					CurrentThreadContext.getCurrentUserName());
			throw new BaseException("没有查到账户信息");
		}
		
		if ("openAccount".equals(operate)) {
			// 开户申请,初始化申请人信息
			// 申请人

			fncGroupCompanyAccountVO.setApplUsrId(CurrentThreadContext.getCurrentUserId());
			fncGroupCompanyAccountVO.setApplUsrNm(CurrentThreadContext.getCurrentUserName());

			// 申请日期
			fncGroupCompanyAccountVO.setApplDate(DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
			// 申请人所属部门
			fncGroupCompanyAccountVO.setApplOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			fncGroupCompanyAccountVO.setApplOrg(CurrentThreadContext.getCurrentOrgShtNm());
		}else if ("closeAccount".equals(operate)) {
			// 销户户申请,初始化申请人信息

			fncGroupCompanyAccountVO.setApplCancelUsrId(CurrentThreadContext.getCurrentUserId());
			fncGroupCompanyAccountVO.setApplCancelUsrNm(CurrentThreadContext.getCurrentUserName());

			// 销户申请日期
			fncGroupCompanyAccountVO.setApplCancelDate(DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
			// 销户申请人所属部门
			fncGroupCompanyAccountVO.setApplCancelOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			fncGroupCompanyAccountVO.setApplCancelOrg(CurrentThreadContext.getCurrentOrgShtNm());
		}

		return "rfbase/account/fncGroupCompanyAccountStartFlow";
	}

	/**
	 * 跳转到集团公司账户流程附件页面Frame
	 */
	@RequestMapping(value = "/toFlow.do")
	public Object toFlow(HttpServletRequest request) {

		StringBuffer p = new StringBuffer();

		Enumeration<String> e = request.getParameterNames();// 获取所有参数名
		while (e.hasMoreElements()) {// 通过Enumeration类中的hasMoreElements()判断是否还有参数名
			String parameterName = e.nextElement(); // 获取当前参数名
			p.append(parameterName).append("=").append(request.getParameter(parameterName)).append("&");
		}

		request.setAttribute("p", p.substring(0,p.length()-1));

		return "rfbase/account/compAccountFlowFrame";
	}
	
	/**
	 * 跳转到集团公司账户流程附件页面
	 */
	@RequestMapping(value = "/toFlowTab.do")
	public Object toFlowTab(HttpServletRequest request) {

		this.toSave(request);

		request.setAttribute("flowType", request.getParameter("flowType"));// 开户流程 openAccount| 销户流程closeAccount
		request.setAttribute("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		request.setAttribute("loginUsrNm", CurrentThreadContext.getCurrentUserName());
		
		String  taskNm= request.getParameter("taskNm");//任务名称
		if("申请人确认邮寄".equals(taskNm) || "移交开户资料".equals(taskNm)
				|| "开户信息审核及加挂拜特判断".equals(taskNm)) {
			request.setAttribute("tabFlag", "101");// 开户流程 
		}else if("运营专员确认接收".equals(taskNm) || "复核网银接收".equals(taskNm)) {
			request.setAttribute("tabFlag", "102");// 开户流程 
		}else if("财务出纳确认接收".equals(taskNm)|| "制单网银接收".equals(taskNm)) {
			request.setAttribute("tabFlag", "103");// 开户流程 
		}else {
			request.setAttribute("tabFlag", "00");// 开户流程 
		}
		
		String from = request.getParameter("from");
		if("open".equals(from)) {//开户页面
			return "rfbase/account/compAccountFlowOpen";
		}if("cancel".equals(from)) {//账户基本信息页面
			return "rfbase/account/compAccountFlowCancel";
		}else {//账户基本信息页面
			return "rfbase/account/compAccountFlowBase";
		}
			
	}
	
	/**
	 * 集团公司账户新增或修改
	 */
	@RequestMapping(value = "/save.do")
	@ResponseBody
	public DataResultVO save(FncGroupCompanyAccountVO fncGroupCompanyAccountVO, HttpServletRequest request) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		Long id;//账户信息主键
		try {
			// 验证
			if (StringUtils.isNotBlank(fncGroupCompanyAccountVO.getBankAccount())) {
				FncGroupCompanyAccountQueryCondition qc = new FncGroupCompanyAccountQueryCondition();
				qc.setBankAccount(fncGroupCompanyAccountVO.getBankAccount());
				qc.setIsDel(0);
				List<FncGroupCompanyAccountVO> fncGroupCompanyAccountVOList = fncGroupCompanyAccountService.selectList(qc);
				if (fncGroupCompanyAccountVO.getId() != null) {//修改
					if (CollectionUtils.isNotEmpty(fncGroupCompanyAccountVOList) && fncGroupCompanyAccountVOList.size() > 0 
							&& !fncGroupCompanyAccountVOList.get(0).getId().equals(fncGroupCompanyAccountVO.getId())) {
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("银行账号重复");
						return result;
					}
				}else {//新增
					if (CollectionUtils.isNotEmpty(fncGroupCompanyAccountVOList) 
							&& fncGroupCompanyAccountVOList.size() > 0 ) {
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("银行账号重复");
						return result;
					}
				}
			}
			
			
			if (fncGroupCompanyAccountVO.getId() != null) {
				// 修改
				FncGroupCompanyAccountVO newFncGroupCompanyAccountVO = fncGroupCompanyAccountService
						.selectById(fncGroupCompanyAccountVO.getId());
				if (newFncGroupCompanyAccountVO == null) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("账户信息不存在");
					return result;
				}

				newFncGroupCompanyAccountVO.setAccountCloseDate(fncGroupCompanyAccountVO.getAccountCloseDate());
				newFncGroupCompanyAccountVO.setAccountOpenDate(fncGroupCompanyAccountVO.getAccountOpenDate());
				newFncGroupCompanyAccountVO.setBank(fncGroupCompanyAccountVO.getBank());
				newFncGroupCompanyAccountVO.setBankName(fncGroupCompanyAccountVO.getBankName());
				newFncGroupCompanyAccountVO.setBankProv(fncGroupCompanyAccountVO.getBankProv());
				newFncGroupCompanyAccountVO.setBankCity(fncGroupCompanyAccountVO.getBankCity());
				newFncGroupCompanyAccountVO.setBankAddress(fncGroupCompanyAccountVO.getBankAddress());
				newFncGroupCompanyAccountVO.setBankNature(fncGroupCompanyAccountVO.getBankNature());
				newFncGroupCompanyAccountVO.setBankAccount(fncGroupCompanyAccountVO.getBankAccount());
				newFncGroupCompanyAccountVO.setBankUse(fncGroupCompanyAccountVO.getBankUse());
				newFncGroupCompanyAccountVO.setBuOrgcd(fncGroupCompanyAccountVO.getBuOrgcd());
				newFncGroupCompanyAccountVO.setCstMgr(fncGroupCompanyAccountVO.getCstMgr());
				newFncGroupCompanyAccountVO.setCurrency(fncGroupCompanyAccountVO.getCurrency());
				newFncGroupCompanyAccountVO.setGroupCompanyId(fncGroupCompanyAccountVO.getGroupCompanyId());
				newFncGroupCompanyAccountVO.setIsNetBank(fncGroupCompanyAccountVO.getIsNetBank());
				newFncGroupCompanyAccountVO.setIsOnlineAccount(fncGroupCompanyAccountVO.getIsOnlineAccount());
				newFncGroupCompanyAccountVO.setMdfTm(new Date());
				newFncGroupCompanyAccountVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());

				newFncGroupCompanyAccountVO.setApplDate(fncGroupCompanyAccountVO.getApplDate());
				newFncGroupCompanyAccountVO.setApplOrg(fncGroupCompanyAccountVO.getApplOrg());
				newFncGroupCompanyAccountVO.setApplOrgCd(fncGroupCompanyAccountVO.getApplOrgCd());
				newFncGroupCompanyAccountVO.setApplPhone(fncGroupCompanyAccountVO.getApplPhone());
				newFncGroupCompanyAccountVO.setApplReason(fncGroupCompanyAccountVO.getApplReason());
				newFncGroupCompanyAccountVO.setApplUsrId(fncGroupCompanyAccountVO.getApplUsrId());
				newFncGroupCompanyAccountVO.setApplUsrNm(fncGroupCompanyAccountVO.getApplUsrNm());

				newFncGroupCompanyAccountVO.setApplCancelDate(fncGroupCompanyAccountVO.getApplCancelDate());
				newFncGroupCompanyAccountVO.setApplCancelOrg(fncGroupCompanyAccountVO.getApplCancelOrg());
				newFncGroupCompanyAccountVO.setApplCancelOrgCd(fncGroupCompanyAccountVO.getApplCancelOrgCd());
				newFncGroupCompanyAccountVO.setApplCancelPhone(fncGroupCompanyAccountVO.getApplCancelPhone());
				newFncGroupCompanyAccountVO.setApplCancelReason(fncGroupCompanyAccountVO.getApplCancelReason());
				newFncGroupCompanyAccountVO.setApplCancelUsrId(fncGroupCompanyAccountVO.getApplCancelUsrId());
				newFncGroupCompanyAccountVO.setApplCancelUsrNm(fncGroupCompanyAccountVO.getApplCancelUsrNm());
				//add by gengchunlan 20200114
				newFncGroupCompanyAccountVO.setCorpName(fncGroupCompanyAccountVO.getCorpName());//法人姓名
				newFncGroupCompanyAccountVO.setCorpPhone(fncGroupCompanyAccountVO.getCorpPhone());//法人预留电话
				newFncGroupCompanyAccountVO.setOperName(fncGroupCompanyAccountVO.getOperName());//经办人姓名
				newFncGroupCompanyAccountVO.setOperPhone(fncGroupCompanyAccountVO.getOperPhone());//经办人预留电话
				
				fncGroupCompanyAccountService.update(newFncGroupCompanyAccountVO);
				id=newFncGroupCompanyAccountVO.getId();
			} else {
				// 新增
				fncGroupCompanyAccountVO.setAccountStatus(FncGroupCompanyConstants.FNC_ACCOUNT_STATUS_UNAUDIT);// 账户状态:未审核
				fncGroupCompanyAccountVO.setIsValid(FncGroupCompanyConstants.IS_VALID_YES);
				fncGroupCompanyAccountVO.setIsDel(FncGroupCompanyConstants.IS_DEL_NO);
				fncGroupCompanyAccountVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				fncGroupCompanyAccountVO.setCrtTm(new Date());

				id=fncGroupCompanyAccountService.add(fncGroupCompanyAccountVO);
			}
			result.setData(id);//返回账户id
		} catch (Exception ex) {
			ex.printStackTrace();
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, null, "操作数据失败.DATA:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	/**
	 * 查询集团公司
	 */
	@RequestMapping("/selectById.do")
	@ResponseBody
	public Object selectById(Long id) {
		if (id != null) {
			return fncGroupCompanyAccountService.selectById(id);
		}
		return null;
	}

	/**
	 * 删除集团公司
	 */
	@RequestMapping(value = "/removeById.do")
	@ResponseBody
	public Object removeById(Long id) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			// 验证
			if (id == null) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("id不能为空");
				return result;
			}

			fncGroupCompanyAccountService.removeById(id);

		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, null, "操作数据失败.DATA:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	/**
	 * 发起开户|销户申请流程
	 */
	@RequestMapping(value = "/startFlow.do")
	@ResponseBody
	public Object startFlow(Long id, String operate) {

//		String procDefKey="FLOW_0000_ARC02_001";
//		String procDefId="FLOW_0000_ARC02_001:1:7603537b-21a5-11e8-a7e1-005056b1519e";
//		String procNo="权证借阅申请流程";

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if (StringUtils.isEmpty(id)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, null, SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY,
					CurrentThreadContext.getCurrentUserName());
			return result;
		}

		FncGroupCompanyAccountVO newFncGroupCompanyAccountVO = fncGroupCompanyAccountService.selectById(id);
		if (newFncGroupCompanyAccountVO == null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("账户信息不存在");
			return result;
		}

		if ("openAccount".equals(operate)) {
			// 集团账户开户流程
			if (StringUtils.isNotBlank(newFncGroupCompanyAccountVO.getAccountStatus())) {
				if (!FncGroupCompanyConstants.FNC_ACCOUNT_STATUS_UNAUDIT
						.equals(newFncGroupCompanyAccountVO.getAccountStatus())) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("只有未审核状态,才能发起流程");
					return result;
				}
			}

			// 集团账户状态改为审核中
			newFncGroupCompanyAccountVO.setAccountStatus(FncGroupCompanyConstants.FNC_ACCOUNT_STATUS_AUDITING);
			
		} else {
			// 集团账户销户流程
			if (StringUtils.isNotBlank(newFncGroupCompanyAccountVO.getAccountStatus())) {
				if (!FncGroupCompanyConstants.FNC_ACCOUNT_STATUS_NORMAL
						.equals(newFncGroupCompanyAccountVO.getAccountStatus())) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("只有正常状态,才能发起流程");
					return result;
				}
			}
			
			
			// 集团账户状态改为审核中
			newFncGroupCompanyAccountVO.setAccountStatus(FncGroupCompanyConstants.FNC_ACCOUNT_STATUS_CANCELING);
						
		}

		
		fncGroupCompanyAccountService.update(newFncGroupCompanyAccountVO);

		
		
		/**
		 * 发起流程
		 */
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		try {
			// 流程定义Key和流程定义ID 如果是前端选择的则直接指定,如果不是则系统自动按照配置选择唯一一条记录,如果找不到会提示
			flowStartParamsDTO.setBusinessKey(String.valueOf(id));
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
			flowStartParamsDTO.setWordsInTheTable(FriBaseInfoConstant.REF_FLOW_S_H_FRI);
			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
			flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);// 优先级,可以在界面定义

			if ("openAccount".equals(operate)) {
				// 集团账户开户流程
				flowStartParamsDTO.setModelTyp(FncGroupCompanyConstants.FLOW_MODEL_TYP_OPEN_ACCOUNT);// 需要和流程配置中的模块类型匹配
			} else {
				// 集团账户销户流程
				flowStartParamsDTO.setModelTyp(FncGroupCompanyConstants.FLOW_MODEL_TYP_CLOSE_ACCOUNT);
			}

			// 设置关键字 开始
			StringBuffer keyWords = new StringBuffer();

			flowStartParamsDTO.setSearchDesc(keyWords.toString());
			BaseLogUtils.info(logger, "borrowApplyStartFlow", "keyWords：" + keyWords.toString(),
					CurrentThreadContext.getCurrentUserName());
			// 设置关键字 结束

			/**
			 * 1、发起人为客户经理(manager),流程：业务发起人（客户经理）-合同管理员-省总-事业部风控（重卡沈旭东）-权证寄出
			 * 2、发起人为非客户经理(noManager),流程：后台发起人（事业部成员）-直属领导-权证寄出
			 */
			Map<String, Object> startParams = new HashMap<String, Object>();
			startParams.put("originator", "noManager");// 默认非客户经理(noManager)

//			if(entity != null && StringUtils.isNotBlank(entity.getContractNo())) {
//				PrjBscInfoQueryCondition qc = new PrjBscInfoQueryCondition();
//				qc.setCntNo(entity.getContractNo());
//				List<PrjBscInfoVO> prjBscInfoVOList = prjBscInfoService.searchPrjBscInfoList(qc);
//				if(prjBscInfoVOList != null && prjBscInfoVOList.size() >0) {
//					for (PrjBscInfoVO prjBscInfoVO : prjBscInfoVOList) {
//						if(prjBscInfoVO.getCstMgrId() != null && prjBscInfoVO.getCstMgrId().equals(CurrentThreadContext.getCurrentUserId())) {
//							startParams.put("originator", "manager");
//							break;
//						}
//					}
//				}
//			}
			//add 是否为资金部  isFund （1 是  0否） by gengchunlan 20191030
			startParams.put("isFund", "1");//默认 资金部 00001008
			Object object = CurrentThreadContext.getValue(CurrentThreadContext.CURRENT_ORG_CD);//当前组织机构代码
			BaseLogUtils.info(logger, "startFlow", "scurrentOrgCd：" +object.toString()+"startParams"+startParams.toString(), CurrentThreadContext.getCurrentUserName());
			String currentOrgCd = (String)object;
			  if(StringUtils.isNotBlank(currentOrgCd)) { 
				  if(currentOrgCd.length()==8) {
					  if(!"00001008".equals(currentOrgCd)) { 
						  startParams.put("isFund", "0");//非资金部
					  }
				  }
				  if(currentOrgCd.length()<8){ 
					  startParams.put("isFund", "0");//非资金部
				  }
				  if(currentOrgCd.length()>8){ 
					  String linStr= currentOrgCd.substring(0, 8);
					  if(!"00001008".equals(linStr)) { 
						  startParams.put("isFund", "0");//非资金部 
					  }
				  }
			  } 
			  BaseLogUtils.info(logger, "startFlow", "sncurrentOrgCd：" +object.toString()+"startParams"+startParams.toString(), CurrentThreadContext.getCurrentUserName());
			//end by gengchunlan 20191030

			 //事业部审批:通过后,需要判断是否为物流事业部
			startParams.put("wuliu",0);//默认非物流事业部00000011 
			if(StringUtils.isNotBlank(currentOrgCd)) { 
				  if(currentOrgCd.length()==8) {
					  if("00000011".equals(currentOrgCd)) { 
						  startParams.put("wuliu", "1");//物流事业部
					  }
				  }else if(currentOrgCd.length()>8){ 
					  if("00000011".equals(currentOrgCd.substring(0, 8))) { 
						  startParams.put("wuliu", "1");//物流事业部
					  }
				  }
			  }   
			BaseLogUtils.info(logger, "", "startParams"+startParams.toString(), CurrentThreadContext.getCurrentUserName());
			
			  
			flowStartParamsDTO.setStartParams(startParams);

			DataResultDTO dataResultDTO = this.fncGroupCompanyAccountService.addFlowStart(flowStartParamsDTO);
			if (!dataResultDTO.getCode().equals(BaseExceptionConstant.BASE_EXCEPTION_CODE_200)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
			}
			if (null != dataResultDTO && null != dataResultDTO.getData()) {
				FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO.getData();
				if (StringUtils.isNotBlank(flowStartedDTO.getNextOperUsrNames())) {
					result.setInfo("下一个节点操作人:" + flowStartedDTO.getNextOperUsrNames());
				} else {
					result.setInfo("流程发起成功");
				}
			}

		} catch (BaseException e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(e.getMessage());
			BaseLogUtils.info(logger, null, "错误[BaseException],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO)
					+ " -ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
			e.getStackTrace();
		} catch (Exception e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, null,
					"错误[Exception],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO) + " -ERROR:" + e.getMessage(),
					CurrentThreadContext.getCurrentUserName());
			e.getStackTrace();
		}
		return result;
	}

	/**
	 * 流程列表页面
	 */
	@RequestMapping(value = "/toFlowList.do")
	public Object toFlowList(HttpServletRequest request) {

		request.setAttribute("id", request.getParameter("id"));
		return "rfbase/account/fncGroupCompanyAccountFlowList";
	}

	/**
	 * 流程列表数据
	 */
	@RequestMapping("/getFlowListPage.do")
	@ResponseBody
	public Object getFlowListPage(FncGroupCompanyAccountQueryCondition qc, HttpServletRequest request) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");

		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		page.setCondition(qc);

		page = this.fncGroupCompanyAccountService.getFlowListPage(page);
		List<Map<String, Object>> list = (List<Map<String, Object>>) page.getResultList();
		BaseLogUtils.info(logger, "borrowFlowPage", "查询数据完成. DATA:" + JSONObject.toJSONString(page),
				CurrentThreadContext.getCurrentUserName());
		return new ListPageVO<Map<String, Object>>(list, page.getTotalCount());
	}
	
	/**
	 * 银行列表
	 */
	@RequestMapping("/getBankList.do")
	@ResponseBody
	public Object getBankList(HttpServletRequest request) {

		// 开户银行(数据字典)
		List<KeyValueVO> bankList = sysDictionaryApiService.getKvList(FncGroupCompanyConstants.FNC_BANK,
				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		return bankList;

	}
	/**
	 * 申请人确认邮寄[tabFlag=101] 节点需填写“邮寄信息 运营专员确认接收[tabFlag=102]  财务出纳确认接收[tabFlag=103]
	 */
	@RequestMapping(value = "/updatePartInfo.do")
	@ResponseBody
	public DataResultVO updatePartInfo(FncGroupCompanyAccountVO fncGroupCompanyAccountVO, HttpServletRequest request) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		/*
		 * "handWay":handWay, "postInfo":postInfo, "receiver":receiver,
		 * "postData":postData, "onlineBankNum":onlineBankNum,
		 * "onlineBankSingle":onlineBankSingle, "onlineBankReviewer":onlineBankReviewer
		 */
		try {
			//验证
			if (fncGroupCompanyAccountVO.getId() != null) {
				if(StringUtils.isNotBlank(fncGroupCompanyAccountVO.getOnlineBankSingle())
						&& StringUtils.isNotBlank(fncGroupCompanyAccountVO.getOnlineBankReviewer())
						&& fncGroupCompanyAccountVO.getOnlineBankSingle().equals(fncGroupCompanyAccountVO.getOnlineBankReviewer())) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("网银制单人和复核人不能为同一人");
					return result;
				}
				
				
				// 修改
				FncGroupCompanyAccountVO newFncGroupCompanyAccountVO = fncGroupCompanyAccountService
						.selectById(fncGroupCompanyAccountVO.getId());
				if (newFncGroupCompanyAccountVO == null) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("账户信息不存在");
					return result;
				}
				newFncGroupCompanyAccountVO.setHandWay(fncGroupCompanyAccountVO.getHandWay());
				newFncGroupCompanyAccountVO.setPostInfo(fncGroupCompanyAccountVO.getPostInfo());
				newFncGroupCompanyAccountVO.setReceiver(fncGroupCompanyAccountVO.getReceiver());
				newFncGroupCompanyAccountVO.setPostData(fncGroupCompanyAccountVO.getPostData());
				newFncGroupCompanyAccountVO.setOnlineBankNum(fncGroupCompanyAccountVO.getOnlineBankNum());
				newFncGroupCompanyAccountVO.setOnlineBankSingle(fncGroupCompanyAccountVO.getOnlineBankSingle());
				newFncGroupCompanyAccountVO.setOnlineBankReviewer(fncGroupCompanyAccountVO.getOnlineBankReviewer());
				fncGroupCompanyAccountService.update(newFncGroupCompanyAccountVO);
			} 
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, null, "操作数据失败.DATA:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	/**
	 * 是否停用:启用或停用
	 */
	@RequestMapping(value = "/updateIsStopUse.do")
	@ResponseBody
	public DataResultVO updateIsStopUse(Long id,Integer isStopUse) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		
		BaseLogUtils.info(logger, "", "updateIsStopUse:id:" + id+",isStopUse:"+isStopUse,
				CurrentThreadContext.getCurrentUserName());
		
		if (id == null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("集团公司账户id不能为空");
			return result;
		}
		if (isStopUse == null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("是否停用isStopUse不能为空");
			return result;
		}
		if (isStopUse != 1 && isStopUse != 0) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("是否停用isStopUse只能为1或0()");
			return result;
		}
		
		try {
				FncGroupCompanyAccountVO fncGroupCompanyAccountVO = fncGroupCompanyAccountService.selectById(id);
				if (fncGroupCompanyAccountVO == null) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("集团公司账户信息不存在");
					return result;
				}
				
				BaseLogUtils.info(logger, "", "更新前fncGroupCompanyAccountVO:" + JSONObject.toJSONString(fncGroupCompanyAccountVO),
						CurrentThreadContext.getCurrentUserName());
				
				fncGroupCompanyAccountVO.setIsStopUse(isStopUse);

				fncGroupCompanyAccountService.update(fncGroupCompanyAccountVO);
				
				BaseLogUtils.info(logger, "", "更新后fncGroupCompanyAccountVO:" + JSONObject.toJSONString(fncGroupCompanyAccountVO),
						CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			ex.printStackTrace();
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, null, "操作数据失败.:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}
	
}
